package com.changgou.web.getaway.filter;

import com.changgou.web.getaway.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * 鉴权网关, 鉴定消费者有没有权限访问我们系统
 * 有权限放行, 没权限拦截
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthService authService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求
        ServerHttpRequest request = exchange.getRequest();
        //2. 获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3. 获取消费者访问路径
        String path = request.getURI().getPath();

        //4. 判断访问路径如果是登录的路径, 或者是去畅购首页, 搜索页,
        // 详情页等路径放行, 其他路径拦截住进行下面的业务处理
        //
        if (path.contains("/oauth/toLogin") || path.contains("/oauth/login") || !UrlFilter.hasAuthorize(path)) {
            return chain.filter(exchange);
        }

        //5. 获取消费者浏览器cookie中的短令牌jti, 如果获取不到跳转到登录页面重新登录
        String jti = authService.getJtiFromCookie(request);
        if (StringUtils.isEmpty(jti)) {
            //跳转到登录系统从新登录
            //设置响应的状态码
            response.setStatusCode(HttpStatus.SEE_OTHER);
            //设置响应头内容, http协议规定如果响应头的key是Location, value就是重定向的地址
            response.getHeaders().set("Location", "http://web.changgou.com:8001/api/oauth/toLogin?ReturnUrl=" + request.getURI());
            return response.setComplete();
        }

        //6. 通过jti短令牌到redis中获取jwt长令牌, 长令牌获取不到, 跳转到登录页面重新登录
        String jwt = authService.getJwtByJtiFromRedis(jti);
        if (StringUtils.isEmpty(jwt)) {
            //跳转到登录系统从新登录
            //设置响应的状态码
            response.setStatusCode(HttpStatus.SEE_OTHER);
            //设置响应头内容
            response.getHeaders().set("Location", "http://web.changgou.com:8001/api/oauth/toLogin?ReturnUrl=" + request.getURI());
            return response.setComplete();
        }

        //7. 将jwt长令牌放入当前请求的请求头中, 放行
        request.mutate().header("authorization", "Bearer" + jwt);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
